package com.bwda.dsrs.filecenter.controller;

import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.base.util.StringUtil;
import com.bwda.dsrs.filecenter.condition.DbScanTableHandleParams;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.dataleveltyperel.DataLevelTypeRelCondition;
import com.bwda.dsrs.filecenter.domain.condition.datasensitivewords.DataSensitiveWordsCondition;
import com.bwda.dsrs.filecenter.domain.condition.datatypewordrel.DataTypeWordRelCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbgroup.DbGroupCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbgrouprel.DbGroupRelCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbinfo.DbInfoCondition;
import com.bwda.dsrs.filecenter.domain.condition.dbscanresult.DbScanResultCondition;
import com.bwda.dsrs.filecenter.domain.condition.tabletags.TableTagsCondition;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import com.bwda.dsrs.filecenter.domain.form.scanresulttable.TableTagCreatForm;
import com.bwda.dsrs.filecenter.domain.form.dbscanresult.DbScanResultCreateForm;
import com.bwda.dsrs.filecenter.domain.form.dbscanresult.DbScanResultQueryForm;
import com.bwda.dsrs.filecenter.domain.form.dbscanresult.DbScanResultUpdateForm;
import com.bwda.dsrs.filecenter.domain.po.dataleveltyperel.DataLevelTypeRelPo;
import com.bwda.dsrs.filecenter.domain.po.datasensitivewords.DataSensitiveWordsPo;
import com.bwda.dsrs.filecenter.domain.po.datatype.DataTypePo;
import com.bwda.dsrs.filecenter.domain.po.datatypewordrel.DataTypeWordRelPo;
import com.bwda.dsrs.filecenter.domain.po.dbgroup.DbGroupPo;
import com.bwda.dsrs.filecenter.domain.po.dbgrouprel.DbGroupRelPo;
import com.bwda.dsrs.filecenter.domain.po.dbinfo.DbInfoPo;
import com.bwda.dsrs.filecenter.domain.po.dbscanresult.DbScanResultPo;
import com.bwda.dsrs.filecenter.domain.po.scanresulttable.ScanResultTablePo;
import com.bwda.dsrs.filecenter.domain.po.tabletags.TableTagsPo;
import com.bwda.dsrs.filecenter.domain.vo.datatype.DataTypeVo;
import com.bwda.dsrs.filecenter.domain.vo.dbscanresult.DbScanResultColumnListVo;
import com.bwda.dsrs.filecenter.domain.vo.dbscanresult.DbScanResultTableColumnListVo;
import com.bwda.dsrs.filecenter.domain.vo.dbscanresult.DbScanResultTableListVo;
import com.bwda.dsrs.filecenter.domain.vo.dbscanresult.DbScanResultVo;
import com.bwda.dsrs.filecenter.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Db scan result controller
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/b/dbscanresult")
@Api(value = "/b/dbscanresult", tags = "敏感字段扫描结果表")
public class DbScanResultController extends BaseController {

    @Autowired
    private DbScanResultService dbScanResultService;
    @Autowired
    private DataSensitiveWordsService dspDataSensitiveWordsService;
    @Autowired
    private DbInfoService dbInfoService;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private DataTypeWordRelService dataTypeWordRelService;
    @Autowired
    private DataTypeService dataTypeService;
    @Autowired
    private DataLevelTypeRelService dataLevelTypeRelService;
    @Autowired
    private DbGroupService dbGroupService;
    @Autowired
    private DbGroupRelService dbGroupRelService;
    @Autowired
    private TagsService tagsService;
    @Autowired
    private TableTagsService tableTagsService;
    @Autowired
    private ScanResultTableService tableService;


    //	@Autowired
//	private RedisTemplate redisTemplate;
    @Value("${scan_rownum}")
    private Integer scanRownum;

    /**
     * Query response entity
     *
     * @param scanResultId scan result id
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感字段扫描结果表", notes = "查询敏感字段扫描结果表", httpMethod = "GET")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DbScanResultVo> query(@ApiParam(value = "id", required = true) @RequestParam Integer scanResultId) throws BusinessServiceException {
        DbScanResultPo po = dbScanResultService.queryWithValid(scanResultId);
        DbScanResultVo vo = CopyUtil.transfer(po, DbScanResultVo.class);
        return getSuccessResult(vo);
    }

    /**
     * Query count response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感字段扫描结果表数量", notes = "查询敏感字段扫描结果表数量", httpMethod = "GET")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        DbScanResultCondition condition = this.getConditionByQueryForm(form);
        int count = dbScanResultService.queryCount(condition);
        return getSuccessResult(count);
    }

    /**
     * Query list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感字段扫描结果表列表", notes = "查询敏感字段扫描结果表列表", httpMethod = "GET")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<DbScanResultVo>> queryList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        DbScanResultCondition condition = this.getConditionByQueryForm(form);
        List<DbScanResultPo> poList = dbScanResultService.queryList(condition);
        List<DbScanResultVo> voList = CopyUtil.transfer(poList, DbScanResultVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    /**
     * Query page list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感字段扫描结果表列表(带分页)", notes = "查询敏感字段扫描结果表列表(带分页)", httpMethod = "GET")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<DbScanResultVo>> queryPageList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        DbScanResultCondition condition = this.getConditionByQueryForm(form);
        List<DbScanResultVo> voList = new ArrayList<>();
        int count = dbScanResultService.queryCount(condition);
        if (count > 0) {
            List<DbScanResultPo> poList = dbScanResultService.queryList(condition);
            voList = CopyUtil.transfer(poList, DbScanResultVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }

    /**
     * Add response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "新增敏感字段扫描结果表", notes = "新增敏感字段扫描结果表", httpMethod = "POST")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DbScanResultVo> add(@ModelAttribute @Valid DbScanResultCreateForm form) throws BusinessServiceException {
        DbScanResultPo po = CopyUtil.transfer(form, DbScanResultPo.class);
//		po.setScanResultId(RandomUtils.nextInt());
        dbScanResultService.insert(po);
        DbScanResultVo vo = CopyUtil.transfer(po, DbScanResultVo.class);
        return getSuccessResult(vo);
    }

    /**
     * Update response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "修改敏感字段扫描结果表", notes = "修改敏感字段扫描结果表", httpMethod = "POST")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity update(@ModelAttribute @Valid DbScanResultUpdateForm form) throws BusinessServiceException {
        DbScanResultPo po = CopyUtil.transfer(form, DbScanResultPo.class);
        if (StringUtils.isNotBlank(form.getWordIds()) && "0".equals(form.getWordIds())) {
            po.setWordIds("");
            po.setMatchNums(0);
        }
        //如果人工操作，识别类型修改成 人工识别，否则默认是自动识别
        if (po.getIsApprove() != null) {
            if (po.getIsApprove() >= 1) {
                po.setDiscernType(1);
            } else {
                po.setDiscernType(0);
            }

        }
        dbScanResultService.update(po);
        return getSuccessResult();
    }

    @ApiOperation(value = "表绑定标签", notes = "字段绑定标签", httpMethod = "POST")
    @RequestMapping(value = "/bindTags", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity bindTags(@ModelAttribute @Valid TableTagCreatForm form) throws BusinessServiceException {
        String[] tagIdArray = form.getTagIds().split(",");

        ScanResultTablePo po = tableService.queryWithValid(form.getTableId());

        TableTagsCondition tableTagsCondition = new TableTagsCondition();
        tableTagsCondition.setTableId(po.getId());
        List<TableTagsPo> tableTagsPos = tableTagsService.queryList(tableTagsCondition);
        for (TableTagsPo tableTagsPo : tableTagsPos) {
            tableTagsService.delete(tableTagsPo.getTableTagId());
        }

        for(String tagId:tagIdArray){
            if(StringUtils.isNotEmpty(tagId)){
                TableTagsPo tableTagsPo = new TableTagsPo();
                tableTagsPo.setTableTagId(tableTagsService.queryId());
                tableTagsPo.setTableId(form.getTableId());
                tableTagsPo.setTagId(Integer.parseInt(tagId));
                tableTagsService.insert(tableTagsPo);

            }
        }


        return getSuccessResult();
    }

    /**
     * Delete response entity
     *
     * @param scanResultId scan result id
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "删除敏感字段扫描结果表", notes = "删除敏感字段扫描结果表", httpMethod = "POST")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity delete(@ApiParam(value = "id", required = true) @RequestParam Integer scanResultId) throws BusinessServiceException {
        dbScanResultService.delete(scanResultId);
        return getSuccessResult();
    }

    /**
     * Query table name list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感字段扫描结果表表名称", notes = "查询敏感字段扫描结果表表名称", httpMethod = "GET")
    @RequestMapping(value = "/queryTableNameList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<String>> queryTableNameList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        List<String> voList = new ArrayList<>();
        DbScanResultCondition dbScanResultCondition = this.getConditionByQueryForm(form);
        dbScanResultCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        //获取不同表
        List<DbScanResultPo> distinctTableList = dbScanResultService.queryDistinctTableList(dbScanResultCondition);
        if (!CollectionUtils.isEmpty(distinctTableList)) {
            voList = distinctTableList.stream().map(p -> p.getTableName()).collect(Collectors.toList());
        }
        return getSuccessResult(getListResponse(voList));
    }

    /**
     * Query table list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感字段扫描结果表", notes = "查询敏感字段扫描结果表", httpMethod = "GET")
    @RequestMapping(value = "/queryTableList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<DbScanResultTableListVo>> queryTableList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        //获取敏感字段
        DataSensitiveWordsCondition dataSensitiveWordsCondition = new DataSensitiveWordsCondition();
        dataSensitiveWordsCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        List<DataSensitiveWordsPo> dataSensitiveWordsPos = dspDataSensitiveWordsService.queryList(dataSensitiveWordsCondition);
        DbInfoCondition dbInfoCondition = new DbInfoCondition();
        dbInfoCondition.setPageNum(form.getPageNum());
        dbInfoCondition.setPageSize(form.getPageSize());
        dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        dbInfoCondition.setDbId(form.getDbId());
        int count = dbInfoService.queryCount(dbInfoCondition);
        List<DbScanResultTableListVo> voList = new ArrayList<>();
        if (count > 0) {
            List<DbInfoPo> dbInfoPoList = dbInfoService.queryList(dbInfoCondition);
            if (!CollectionUtils.isEmpty(dbInfoPoList)) {
                for (DbInfoPo d : dbInfoPoList
                ) {
                    DbScanResultTableListVo dbList = new DbScanResultTableListVo();
                    dbList.setDbId(d.getDbId());
                    dbList.setDbIp(d.getDbIp());
                    dbList.setDbName(d.getDbName());
                    //获取不同表
                    DbScanResultCondition dbScanResultCondition = new DbScanResultCondition();
                    dbScanResultCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
                    dbScanResultCondition.setDbId(d.getDbId());
                    dbScanResultCondition.setTableName(form.getTableName());
                    dbScanResultCondition.setMatchNums(form.getMatchNums());
                    List<DbScanResultPo> distinctTableList = dbScanResultService.queryDistinctTableList(dbScanResultCondition);
                    if (!CollectionUtils.isEmpty(distinctTableList)) {
                        List<DbScanResultTableListVo.TableList> tableLists = new ArrayList<>();
                        for (DbScanResultPo dbScanResultPo : distinctTableList) {
                            DbScanResultTableListVo.TableList tableList = new DbScanResultTableListVo.TableList();
                            tableList.setTableName(dbScanResultPo.getTableName());
                            List<Integer> wordsIds = getWordsByTableName(dbScanResultPo.getDbId(), dbScanResultPo.getTableName());
                            tableList.setLabel(getNamesByWordIds(dataSensitiveWordsPos, wordsIds));
                            tableList.setDataTypeVoList(CopyUtil.transfer(getDataTypePoByTypeIds(getTypeIdByWordIds(wordsIds)), DataTypeVo.class));
                            tableLists.add(tableList);
                        }
                        dbList.setTableLists(tableLists);
                    }
                    voList.add(dbList);
                }
            }
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }


    /**
     * Query column list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感扫描结果表字段", notes = "查询敏感扫描结果表字段", httpMethod = "GET")
    @RequestMapping(value = "/queryColumnList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<DbScanResultColumnListVo>> queryColumnList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        List<DbScanResultColumnListVo> voList = new ArrayList<>();
        DbScanResultCondition dbScanResultCondition = this.getConditionByQueryForm(form);
        dbScanResultCondition.setDbId(form.getDbId());
        dbScanResultCondition.setTableNameLikeFlag(false);
        dbScanResultCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        int count = dbScanResultService.countSensColumn(dbScanResultCondition);
        if (count > 0) {
            DataSensitiveWordsCondition dataSensitiveWordsCondition = new DataSensitiveWordsCondition();
            dataSensitiveWordsCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
            List<DbScanResultPo> dbScanResultPos = dbScanResultService.queryTableeColumnList(dbScanResultCondition);
            if (!CollectionUtils.isEmpty(dbScanResultPos)) {
                List<DataSensitiveWordsPo> dataSensitiveWordsPos = new ArrayList<>();
                for (DbScanResultPo d : dbScanResultPos
                ) {
                    DbScanResultColumnListVo dbScanResultColumnListVo = new DbScanResultColumnListVo();
                    dbScanResultColumnListVo.setColumnName(d.getColumnName());
                    dbScanResultColumnListVo.setRemark(d.getRemark());
                    dbScanResultColumnListVo.setColumnRemark(d.getColumnRemark());
                    if (StringUtils.isNotBlank(d.getWordIds())) {
                        dataSensitiveWordsCondition.setWordId(Integer.valueOf(d.getWordIds()));
                        dataSensitiveWordsPos = dspDataSensitiveWordsService.queryList(dataSensitiveWordsCondition);
                    }
                    if (!CollectionUtils.isEmpty(dataSensitiveWordsPos)) {
                        dbScanResultColumnListVo.setLabel(dataSensitiveWordsPos.get(0).getName());
                    }
                    voList.add(dbScanResultColumnListVo);
                }
            }
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }

    /**
     * Query table column list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "查询敏感扫描结果表所有数据", notes = "查询敏感扫描结果表所有数据", httpMethod = "GET")
    @RequestMapping(value = "/queryTableColumnList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<DbScanResultTableColumnListVo>> queryTableColumnList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        List<DbScanResultTableColumnListVo> voList = new ArrayList<>();
        DbScanResultCondition dbScanResultCondition = this.getConditionByQueryForm(form);
        dbScanResultCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        int count = 0;
        DbGroupCondition dbGroupCondition = new DbGroupCondition();
        dbGroupCondition.setPageSize(Integer.MAX_VALUE);
//        if (!"sysadmin".equals(getUserCode())) {
//            dbGroupCondition.setAdminUserCode(getUserCode());
//        }
//        dbGroupCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
//        dbGroupCondition.setStatus(BusinessConstants.NumberConstant.ZERO);
        List<DbGroupPo> dbGroupPos = dbGroupService.queryList(dbGroupCondition);
        if (!CollectionUtils.isEmpty(dbGroupPos)) {
            DbGroupRelCondition dbGroupRelCondition = new DbGroupRelCondition();
            dbGroupRelCondition.setPageSize(Integer.MAX_VALUE);
            dbGroupRelCondition.setGroupIdList(dbGroupPos.stream().map(dbGroupPo -> dbGroupPo.getId()).distinct().collect(Collectors.toList()));
            List<DbGroupRelPo> dbGroupRelPos = dbGroupRelService.queryList(dbGroupRelCondition);
            if (!CollectionUtils.isEmpty(dbGroupRelPos)) {
                DbInfoCondition dbInfoCondition = new DbInfoCondition();
                dbInfoCondition.setPageSize(Integer.MAX_VALUE);
                dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
                if (StringUtil.isNotEmpty(dbScanResultCondition.getDbName())) {
                    //数据库名
                    dbInfoCondition.setDbName(dbScanResultCondition.getDbName());
                }
                if (StringUtil.isNotEmpty(dbScanResultCondition.getDbType())) {
                    dbInfoCondition.setDbType(dbScanResultCondition.getDbType());
                }
                dbInfoCondition.setDbIdList(dbGroupRelPos.stream().map(dbGroupRelPo -> dbGroupRelPo.getDbId()).distinct().collect(Collectors.toList()));
                //数据库组
                List<DbInfoPo> dbInfoPos = dbInfoService.queryLists(dbInfoCondition);
                if (!CollectionUtils.isEmpty(dbInfoPos)) {
                    dbScanResultCondition.setDbIdList(dbInfoPos.stream().map(dbInfoPo -> dbInfoPo.getDbId()).collect(Collectors.toList()));
                    count = dbScanResultService.countSensColumn(dbScanResultCondition);
                    if (count > 0) {
                        DataSensitiveWordsCondition dataSensitiveWordsCondition = new DataSensitiveWordsCondition();
                        dataSensitiveWordsCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
                        List<DbScanResultPo> dbScanResultPos = dbScanResultService.queryTableeColumnList(dbScanResultCondition);
                        if (!CollectionUtils.isEmpty(dbScanResultPos)) {
                            for (DbScanResultPo d : dbScanResultPos
                            ) {
                                DbScanResultTableColumnListVo dbScanResultColumnListVo = new DbScanResultTableColumnListVo();
                                dbScanResultColumnListVo.setDbId(d.getDbId());
                                DbInfoPo dbInfoPo = dbInfoService.query(d.getDbId());
                                dbScanResultColumnListVo.setDbName(dbInfoPo.getDbName());
                                dbScanResultColumnListVo.setColumnType(d.getColumnType());
                                dbScanResultColumnListVo.setTableName(d.getTableName());
                                dbScanResultColumnListVo.setColumnName(d.getColumnName());
                                dbScanResultColumnListVo.setColumnRemark(d.getColumnRemark());
                                dbScanResultColumnListVo.setDbType(d.getDbType());
                                dbScanResultColumnListVo.setCreateTime(d.getCreateTime());
                                dbScanResultColumnListVo.setRemark(d.getRemark());
                                dbScanResultColumnListVo.setIsApprove(d.getIsApprove());
                                dbScanResultColumnListVo.setScanResultId(d.getScanResultId());
                                dbScanResultColumnListVo.setDiscernType(d.getDiscernType());

                                if (StringUtils.isNotBlank(d.getWordIds())) {
                                    dataSensitiveWordsCondition.setWordId(Integer.valueOf(d.getWordIds()));
                                    List<DataSensitiveWordsPo> dataSensitiveWordsPos = dspDataSensitiveWordsService.queryList(dataSensitiveWordsCondition);
                                    if (!CollectionUtils.isEmpty(dataSensitiveWordsPos)) {
                                        dbScanResultColumnListVo.setLabel(dataSensitiveWordsPos.get(0).getName());
                                    }
                                    dbScanResultColumnListVo.setDataTypeVoList(CopyUtil.transfer(getDataTypePoByTypeIds(getTypeIdByWordIds(Integer.valueOf(d.getWordIds()))), DataTypeVo.class));
                                }
                                voList.add(dbScanResultColumnListVo);
                            }
                        }
                    }
                }
            }
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }
    private List<DbInfoPo> getDbInfoPoList(DbScanResultCondition dbScanResultCondition) throws BusinessServiceException {
        List<DbInfoPo> dbInfoPos = null;
        if ("sysadmin".equals(getUserCode())) {
            DbInfoCondition dbInfoCondition = new DbInfoCondition();
            dbInfoCondition.setPageSize(Integer.MAX_VALUE);
            dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
            if (StringUtil.isNotEmpty(dbScanResultCondition.getDbName())) {
                //数据库名
                dbInfoCondition.setDbName(dbScanResultCondition.getDbName());
            }
            if (StringUtil.isNotEmpty(dbScanResultCondition.getDbType())) {
                dbInfoCondition.setDbType(dbScanResultCondition.getDbType());
            }
            dbInfoPos = dbInfoService.queryLists(dbInfoCondition);
        }
        else{
            DbGroupCondition dbGroupCondition = new DbGroupCondition();
//        dbGroupCondition.setStatus(BusinessConstants.NumberConstant.ZERO);
            dbGroupCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
            dbGroupCondition.setPageSize(Integer.MAX_VALUE);
            List<DbGroupPo> dbGroupPos = dbGroupService.queryList(dbGroupCondition);
            dbGroupCondition.setAdminUserCode(getUserCode());
            if (!CollectionUtils.isEmpty(dbGroupPos)) {
                DbGroupRelCondition dbGroupRelCondition = new DbGroupRelCondition();
                dbGroupRelCondition.setPageSize(Integer.MAX_VALUE);
                dbGroupRelCondition.setGroupIdList(dbGroupPos.stream().map(dbGroupPo -> dbGroupPo.getId()).distinct().collect(Collectors.toList()));
                List<DbGroupRelPo> dbGroupRelPos = dbGroupRelService.queryList(dbGroupRelCondition);
                if (!CollectionUtils.isEmpty(dbGroupRelPos)) {
                    DbInfoCondition dbInfoCondition = new DbInfoCondition();
                    dbInfoCondition.setPageSize(Integer.MAX_VALUE);
                    dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
                    if (StringUtil.isNotEmpty(dbScanResultCondition.getDbName())) {
                        //数据库名
                        dbInfoCondition.setDbName(dbScanResultCondition.getDbName());
                    }
                    if (StringUtil.isNotEmpty(dbScanResultCondition.getDbType())) {
                        dbInfoCondition.setDbType(dbScanResultCondition.getDbType());
                    }
                    dbInfoCondition.setDbIdList(dbGroupRelPos.stream().map(dbGroupRelPo -> dbGroupRelPo.getDbId()).distinct().collect(Collectors.toList()));
                    //数据库组
                    dbInfoPos = dbInfoService.queryLists(dbInfoCondition);

                }
            }

        }
        return dbInfoPos;
    }
    /**
     * Scan response entity
     *
     * @param dbId db id
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "敏感扫描", notes = "敏感扫描", httpMethod = "GET")
    @RequestMapping(value = "/scan", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> scan(@ApiParam(value = "id", required = true) @RequestParam(value = "dbId", required = false) Integer dbId) throws BusinessServiceException {
        asyncService.asyncScan(dbId, 0, 0, scanRownum);
        return getSuccessResult("操作成功");
    }

    /**
     * Update type and level response entity
     *
     * @param dbId db id
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "更新表级结果数据", notes = "更新表级结果数据", httpMethod = "GET")
    @RequestMapping(value = "/updateTypeAndLevel", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> updateTypeAndLevel(@ApiParam(value = "id", required = true) @RequestParam(value = "dbId", required = false) Integer dbId) throws BusinessServiceException {
//		if(redisTemplate.hasKey("updateTypeAndLevelStatus") && redisTemplate.opsForValue().get("updateTypeAndLevelStatus").equals(BusinessConstants.NumberConstant.ONE)){
//			return getFailResult("正在分析，请稍等");
//		}
//		redisTemplate.opsForValue().set("updateTypeAndLevelStatus",BusinessConstants.NumberConstant.ONE);
        //去redis
        if (StringUtils.isNotBlank(System.getProperty("updateTypeAndLevelStatus")) && "1".equals(System.getProperty("updateTypeAndLevelStatus"))) {
            return getFailResult("正在分析，请稍等");
        }
        System.setProperty("updateTypeAndLevelStatus", "1");
        DbInfoCondition dbInfoCondition = new DbInfoCondition();
        dbInfoCondition.setDbId(dbId);
        dbInfoCondition.setPageSize(Integer.MAX_VALUE);
        dbInfoCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        List<DbInfoPo> dbInfoPoList = dbInfoService.queryList(dbInfoCondition);
        DataSensitiveWordsCondition dataSensitiveWordsCondition = new DataSensitiveWordsCondition();
        dataSensitiveWordsCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        dataSensitiveWordsCondition.setPageSize(Integer.MAX_VALUE);
        List<DataSensitiveWordsPo> dataSensitiveWordsPos = dspDataSensitiveWordsService.queryList(dataSensitiveWordsCondition);
        DataLevelTypeRelCondition dataLevelTypeRelCondition = new DataLevelTypeRelCondition();
        dataLevelTypeRelCondition.setPageSize(Integer.MAX_VALUE);
        List<DataLevelTypeRelPo> dataLevelTypeRelPos = dataLevelTypeRelService.queryList(dataLevelTypeRelCondition);
        List<DataLevelTypeRelPo> dataLevelTypeRelPosSorted = dataLevelTypeRelPos.stream().sorted(Comparator.comparing(DataLevelTypeRelPo::getLevelId).reversed()).collect(Collectors.toList());
        //获取不同表
        DbScanResultCondition dbScanResultCondition = new DbScanResultCondition();
        dbScanResultCondition.setDelFlag(BusinessConstants.NumberConstant.ZERO);
        dbScanResultCondition.setDbId(dbId);
        List<DbScanResultPo> distinctTableList = dbScanResultService.queryDistinctTableList(dbScanResultCondition);
        if (!CollectionUtils.isEmpty(dbInfoPoList) && !CollectionUtils.isEmpty(distinctTableList)) {
            for (DbScanResultPo dbScanResultPo : distinctTableList) {
                DbScanResultCondition tableColumnCondition = new DbScanResultCondition();
                tableColumnCondition.setDbId(dbScanResultPo.getDbId());
                tableColumnCondition.setTableName(dbScanResultPo.getTableName());
                List<DbScanResultPo> dbScanResultPos = dbScanResultService.queryTableeColumnList(tableColumnCondition);
                DbScanTableHandleParams.Builder paramsBuilder = DbScanTableHandleParams.newDbScanTableHandleParams()
                        .db(dbInfoPoList.get(0))
                        .dataSensitiveWordsPos(dataSensitiveWordsPos)
                        .dataLevelTypeRelPos(dataLevelTypeRelPosSorted);
                dbScanResultService.updateTypeAndLevel(dbScanResultPos, paramsBuilder.build());
            }
        }
//		redisTemplate.opsForValue().set("updateTypeAndLevelStatus",BusinessConstants.NumberConstant.ZERO);
        System.setProperty("updateTypeAndLevelStatus", "0");
        return getSuccessResult("操作成功");
    }


    /**
     * DbScanResultQueryForm转换为DbScanResultCondition
     *
     * @param form
     * @return
     */
    private DbScanResultCondition getConditionByQueryForm(DbScanResultQueryForm form) {
        DbScanResultCondition condition = CopyUtil.transfer(form, DbScanResultCondition.class);
        return condition;
    }

    /**
     * @param dbId
     * @param tableName
     * @return
     */
    private List<Integer> getWordsByTableName(Integer dbId, String tableName) {
        DbScanResultCondition dbScanResultCondition = new DbScanResultCondition();
        dbScanResultCondition.setDbId(dbId);
        dbScanResultCondition.setTableName(tableName);
        List<DbScanResultPo> dbScanResultPos1 = dbScanResultService.queryTableeColumnList(dbScanResultCondition);
        List<Integer> wordIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dbScanResultPos1)) {
            for (DbScanResultPo dbScanResultPo : dbScanResultPos1) {
                if (StringUtils.isNotEmpty(dbScanResultPo.getWordIds())) {
                    if (StringUtils.isNotBlank(dbScanResultPo.getWordIds())) {
                        wordIds.add(Integer.parseInt(dbScanResultPo.getWordIds()));
                    }
                }
            }
        }
        return wordIds.stream().distinct().collect(Collectors.toList());
    }

    /**
     * /匹配敏感标签
     *
     * @param dataSensitiveWordsPos
     * @param wordIds
     * @return
     */
    private String getNamesByWordIds(List<DataSensitiveWordsPo> dataSensitiveWordsPos, List<Integer> wordIds) {
        List<String> names = new ArrayList<>();
        for (DataSensitiveWordsPo dataSensitiveWordsPo : dataSensitiveWordsPos
        ) {
            for (Integer id : wordIds) {
                if ((dataSensitiveWordsPo.getWordId().equals(id))) {
                    names.add(dataSensitiveWordsPo.getName());
                }
            }
        }
        return names.stream().collect(Collectors.joining(","));
    }

    /**
     * 敏感字段关联t_dsp_data_type_word_rel
     *
     * @param wordIds
     * @return
     */
    private List<DataTypeWordRelPo> getTypeIdByWordIds(List<Integer> wordIds) {
        List<DataTypeWordRelPo> dataTypeWordRelPo = new ArrayList<>();
        for (Integer w : wordIds
        ) {
            DataTypeWordRelCondition dataTypeWordRelCondition = new DataTypeWordRelCondition();
            dataTypeWordRelCondition.setWordId(w);
            List<DataTypeWordRelPo> dataTypeWordRelPo1 = dataTypeWordRelService.queryList(dataTypeWordRelCondition);
            dataTypeWordRelPo.addAll(dataTypeWordRelPo1);
        }
        return dataTypeWordRelPo;
    }

    //t_dsp_data_type_word_rel关联t_dsp_data_type
    private List<DataTypePo> getDataTypePoByTypeIds(List<DataTypeWordRelPo> dataTypeWordRelPos) {
        List<DataTypePo> dataTypePos = new ArrayList<>();
        for (DataTypeWordRelPo dataTypeWordRelPo : dataTypeWordRelPos
        ) {
            DataTypePo dataTypePo = dataTypeService.query(dataTypeWordRelPo.getTypeId());
            if (dataTypePo != null) {
                dataTypePos.add(dataTypePo);
            }
        }
        return dataTypePos;
    }

    //敏感字段关联t_dsp_data_type_word_rel
    private List<DataTypeWordRelPo> getTypeIdByWordIds(Integer wordId) {
        DataTypeWordRelCondition dataTypeWordRelCondition = new DataTypeWordRelCondition();
        dataTypeWordRelCondition.setWordId(wordId);
        List<DataTypeWordRelPo> dataTypeWordRelPo = dataTypeWordRelService.queryList(dataTypeWordRelCondition);
        return dataTypeWordRelPo;
    }


    /**
     * Query db sr page list response entity
     *
     * @param form form
     * @return the response entity
     * @throws BusinessServiceException business service exception
     */
    @ApiOperation(value = "新查询敏感字段扫描结果表列表(带分页)", notes = "新查询敏感字段扫描结果表列表(带分页)", httpMethod = "GET")
    @RequestMapping(value = "/queryDbSrPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<DbScanResultVo>> queryDbSrPageList(@ModelAttribute @Valid DbScanResultQueryForm form) throws BusinessServiceException {
        DbScanResultCondition condition = this.getConditionByQueryForm(form);
        List<DbScanResultVo> voList = new ArrayList<>();
        int count = dbScanResultService.queryCount(condition);
        if (count > 0) {
            List<DbScanResultPo> poList = dbScanResultService.queryDbSrPageList(condition);
            voList = CopyUtil.transfer(poList, DbScanResultVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }


}